from aiogram import Bot
from fluentogram import TranslatorRunner

from src.bot.services.locale import Localizator
from src.bot.services.tg_helpers import send_tg_message
from src.bot.worker.exception_handler import exception_handler
from src.database.services import SubscriptionService
from src.database.services.user import UserService


@exception_handler
async def notify_expiring_subscription(
    ctx,
) -> None:
    """Отправляем сообщение о истекающем сроке подписки"""

    bot: Bot = ctx["bot"]
    localizator: Localizator = ctx["localizator"]
    user_service: UserService = ctx["user_service"]
    subscription_service: SubscriptionService = ctx["subscription_service"]

    expiring_subscriptions = await subscription_service.get_expiring_subscriptions()
    for subscription in expiring_subscriptions:
        user = await user_service.get_user_by_id(subscription.user_id)
        locale: TranslatorRunner = localizator.get_by_locale(user.lang_code)

        await send_tg_message(
            bot,
            user.telegram_id,
            locale.get("subscription-expiring-msg", end_date=subscription.end_date),
        )
        await subscription_service.update_subscription_notify_sent(subscription.id)
